import React, { useEffect, useMemo, useState } from "react";
import { Modal } from "antd";
import _ from "lodash";
import { CheckOutlined, RollbackOutlined } from "@ant-design/icons";
import { useInitData } from "./use-events";
import { useScemaRender } from "../utils";
import { MetaSorted } from "schema-form";
import { IFormProps } from "@formily/core/esm/types";
import { ISchemaFieldFactoryOptions } from "@formily/react";
interface ModalFormProps {
  editData?: any;
  loading: boolean;
  title: string;
  visible: boolean;
  onCancel: () => any;
  onOk?: (values: any, cb: any) => any;
  modalMetasConfig?: MetaSorted;
  filedConfig?: ISchemaFieldFactoryOptions;
  formConfigs?: IFormProps;
  needFormat?: boolean;
  width?: number;
  needCache?: any;
  type?: any;
  eventMap?: any;
}
const ModalForm = ({
  editData,
  loading,
  title,
  visible,
  onCancel,
  onOk,
  modalMetasConfig,
  filedConfig,
  formConfigs,
  needCache = true,
  needFormat = true,
  width = 900,
  type = "NORAML",
  eventMap,
}: ModalFormProps) => {
  const [value, setValue] = useState<null | any>(null);
  const [fg, setfg] = useState<any>(false);
  let { form, SchemaFormRender } = useScemaRender(
    filedConfig,
    formConfigs,
    "",
    true,
    [fg]
  );
  useEffect(() => {
    if (value === null && editData && visible) {
      setValue(editData);

      console.log("editData", editData);

      form?.setValues({
        ...editData,
      });
    }
    if (!editData) {
      setValue(null);

      form?.reset();
    }
    return () => {
      console.log("清空");
      setValue(null);
    };
  }, [editData, form]);
  let meta = _.cloneDeep(modalMetasConfig);
  if (needFormat) {
    meta = useInitData(meta, null, type, false, eventMap || {});
  }
  return (
    <Modal
      title={title}
      visible={visible}
      width={width}
      destroyOnClose
      onCancel={() => {
        setValue(null);
        form?.reset();
        onCancel();
        setfg(!fg);
      }}
      maskClosable={false}
      confirmLoading={loading}
      onOk={() => {
        form.submit().then((val: any) => {
          const values = form.values;
          onOk &&
            onOk(values, () => {
              console.log("刷新form");
              setValue(null);
              form?.reset();
              // 防止时间差~~
              setTimeout(() => {
                setfg(!fg);
              }, 250);
            });
        });
      }}
      cancelButtonProps={{
        icon: <RollbackOutlined />,
      }}
      okButtonProps={{
        icon: <CheckOutlined />,
      }}
    >
      {meta?.schema && (
        <SchemaFormRender schema={meta?.schema} pageConfig={meta?.pageConfig} />
      )}
    </Modal>
  );
};

export default ModalForm;
